package org.apache.james.hibernate.entity;

import java.util.HashSet;
import java.util.Set;

import org.apache.james.mailboxmanager.Namespace;
import org.apache.james.mailboxmanager.Namespaces;

class NamespacesInfo implements Namespaces {

	Namespace personalDefault;
	Namespace[] personal;
	Namespace[] shared;
	Namespace[] user;

	NamespacesInfo(ImapUserInfo imapUserInfo) {
		this.user = imapUserInfo.getUserNameSpaces().toArray(new Namespace[0]);
		Set<Namespace> sharedSet = new HashSet<Namespace>();
		sharedSet.addAll(imapUserInfo.getSharedNameSpaces());
		for (Group group : imapUserInfo.getGroups()) {
			sharedSet.addAll(group.getSharedNamespaces());
		}
		this.shared =sharedSet.toArray(new Namespace[0]);
		this.personalDefault = createChildNamespace(imapUserInfo.getDefaultNamespace(), imapUserInfo.getName());
		this.personal = new Namespace[user.length];
		for (int i=0;i<personal.length;i++) {
			this.personal[i] = createChildNamespace(user[i], imapUserInfo.getName());
		}
	}

	private static Namespace createChildNamespace(Namespace ns, String name) {
		return new NamespaceImpl(ns.getName() + ns.getHierarchyDelimter() + name);
	}
	

	/**
	 * Personal namespaces, for example: "#mail.username", "#mail02.username"
	 * 
	 */
	@Override
	public Namespace[] getPersonal() {
		return personal;
	}

	/**
	 * The personal default namespace, for example : "#mail.username"
	 */
	@Override
	public Namespace getPersonalDefault() {
		return personalDefault;
	}

	/**
	 * Shared namespaces, for example: "#shared", "#groups"
	 * 
	 */
	@Override
	public Namespace[] getShared() {
		return shared;
	}

	/**
	 * User namespaces, for example: "#mail", "#mail02"
	 * 
	 */
	@Override
	public Namespace[] getUser() {
		return user;
	}

}
